﻿using System.IO;
using Common.Utils.Helper;
using Game.Kernel;
using Game.Logic.Manager;
using UnityEngine;
using Sproto;

namespace Game.Logic.Data
{
    public class GameUserData : GameBaseData
    {
        public CSharpLuaTable UserConfig { private set; get; }
        private readonly string SavePath = string.Concat(Application.persistentDataPath, "/", GameDefine.GAME_CONFIG_USER);

        public GameUserData()
        {
            // 加载用户本地配置
            LoadOrCreateConfig();
            // 注册服务器数据监听
            RegisterServerLinsteners();
        }

        public static GameUserData Create()
        {
            GameUserData inst = new GameUserData();
            //inst.LoadOrCreateConfig();
            return inst;
        }

        #region User Config
        public WriteResult Save()
        {
            return UserConfig.WriteToFileExAsync(SavePath, GameDefine.GAME_CONFIG_USER);
        }

        private void LoadOrCreateConfig()
        {
            if (!File.Exists(SavePath))
            {
                Debug.LogFormat("Load new user data config!");
                UserConfig = CSharpLuaTable.ParseFromStringEx("{}");
                Save();
            }
            else
            {
                Debug.LogFormat("Load user data config {0}!", SavePath);
                UserConfig = CSharpLuaTable.ParseFromFileEx(SavePath);
            }
        }
        #endregion


        #region Server Data
        private void RegisterServerLinsteners()
        {
            GameDataManager.Instance.RegisterServerDataListener("login", OnReceivedLoginData);
        }

        private void OnReceivedLoginData(SprotoObject _login)
        {

        }
        #endregion
    }
}

